const FIFTEEN = Array.from({ length: 15 }, (e, i) => i + 1);
FIFTEEN.push(false);

const arraysEqual = (arr1, arr2) => {
    if (arr1.length !== arr2.length) return false;

    for (let i = arr1.length; i--; ) {
        if (arr1[i] !== arr2[i]) return false;
    }

    return true;
};

new Vue({
    el: "#app",
    data() {
        return {
            mounted: false,
            state: [...FIFTEEN],
        };
    },
    computed: {
        completed() {
            return this.mounted && arraysEqual(FIFTEEN, this.state);
        },
        empty() {
            return this.state.indexOf(false);
        }
    },
    methods: {
        isPlayable(emptyIndex, tileIndex, width) {
            return (
                (emptyIndex % width !== 0 && emptyIndex - 1 === tileIndex) ||
                (emptyIndex % width !== width - 1 &&
                    emptyIndex + 1 === tileIndex) ||
                emptyIndex - width === tileIndex ||
                emptyIndex + width === tileIndex
            );
        },
        updateState(i) {
            const updated = [...this.state];
            updated[this.state.indexOf(false)] = this.state[i];
            updated[i] = false;
            this.state = updated;
        },
        shuffleState() {
            if(this.completed){
                this.state.sort(() => Math.random() - 0.5);
            }
        },
        clickMove(e,i){
            console.log(i);
            if(!this.completed && this.isPlayable(this.empty,i,4)){
                this.updateState(i);
                e.currentTarget.blur();
            }
        }
    },
    mounted () {
        this.mounted = true;
        this.shuffleState();
    },
});
